//
//  BasicViewController.m
//  haolaDoc
//
//  Created by chen on 2017/5/12.
//  Copyright © 2017年 deyi. All rights reserved.
//

#import "BasicViewController.h"
#import "MJRefresh.h"
#import "DetailActivityViewController.h"
#import "ScheduleTableViewCell.h"
@interface BasicViewController ()<UITableViewDelegate,UITableViewDataSource>{
    NSMutableDictionary *_eventsByDate;
    NSMutableDictionary *_eventsByDate2;
    NSMutableDictionary *_eventsByDate3;
    NSDate *_todayDate;
    NSDate *_minDate;
    NSDate *_maxDate;
    NSDate *_dateSelected;
    NSInteger _contentSize;
    
}
/** window */
@property (nonatomic, strong) UIWindow *window;
/** 悬浮按钮 */
@property (nonatomic, strong) UIButton *button;


@end

@implementation BasicViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(!self){
        return nil;
    }
    
    self.title = @"Basic";
    
    return self;
}
-(void)loadData{
    
    NSUserDefaults *userData=[NSUserDefaults standardUserDefaults];
    NSString *userID=[userData objectForKey:@"userId"];
    
    _doctorId=userID;
    NSString *url = [NSString stringWithFormat:@"/docSchedule/getScheByDate?doctorId=%@&date=%@",_doctorId,_date];
    [AppMonitor parseDicByUrl:url withSuccessBlock:^(NSData *successDic) {
        NSArray *dataInfo=[NSJSONSerialization JSONObjectWithData:successDic options:0 error:nil];
        _data2=[self tranformDataArray:dataInfo];
        NSMutableArray *data3=[[NSMutableArray alloc]init];
        [data3 addObjectsFromArray:_data2];
        _data=data3;
        [_calendarTableView reloadData];
        
        
        // [_tableView reloadData];
    }andFailBlock:^(NSData *failDic) {
    }];
    
}
-(NSMutableArray *)tranformDataArray:(NSArray *)dataInfo{
    NSMutableArray *tempArray=[NSMutableArray array];
    for(NSDictionary *dict in dataInfo){
        ScheduleModel *activityModel=[ScheduleModel initWithDictionary:dict];
        [tempArray addObject:activityModel];
    }
    
    return tempArray;
}
- (void)viewDidLoad
{
    
    [super viewDidLoad];
    _month=[[self dateFormatter2] stringFromDate:[NSDate date]];
    _eventsByDate = [NSMutableDictionary new];
    _eventsByDate2 = [NSMutableDictionary new];
    _calendarManager = [JTCalendarManager new];
    _calendarManager.delegate = self;
    _date=[[self dateFormatter]stringFromDate:[NSDate date]];
    
    // Generate random events sort by date using a dateformatter for the demonstration
    [self createEvents];

    [self loadData];
    
    // Create a min and max date for limit the calendar, optional
    [self createMinAndMaxDate];
    
    [_calendarManager setMenuView:_calendarMenuView];
    [_calendarManager setContentView:_calendarContentView];
    [_calendarManager setDate:_todayDate];
    _calendarTableView.rowHeight=90;
    _calendarTableView.delegate=self;
    _calendarTableView.dataSource=self;
    _calendarTableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;

    
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self creatSuspendBtn];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _window.hidden=YES;
    _window=nil;
}
#pragma mark - Buttons callback

//- (IBAction)didGoTodayTouch
//{
//    [_calendarManager setDate:_todayDate];
//}
- (IBAction)didChangeModeTouch:(id)sender {
    _calendarManager.settings.weekModeEnabled = !_calendarManager.settings.weekModeEnabled;
    [_calendarManager reload];
    
    CGFloat newHeight = 300;
    if(_calendarManager.settings.weekModeEnabled){
        
        newHeight = 85.;
        CGRect frame=_calendarTableView.frame;
        //frame.origin.y-=215;
        //frame.size.height+=215;
        frame.origin.y=_calendarContentView.frame.origin.y+2*_calendarContentView.frame.size.height/6;
        frame.size.height=self.view.frame.size.height-frame.origin.y;
        _calendarTableView.frame=frame;
        
        
    }else{
        CGRect frame=_calendarTableView.frame;
        frame.origin.y=_calendarContentView.frame.origin.y+_calendarContentView.frame.size.height+1;
        frame.size.height=self.view.frame.size.height-frame.origin.y;
        _calendarTableView.frame=frame;
        
    }
    

}


#pragma mark - CalendarManager delegate

// Exemple of implementation of prepareDayView method
// Used to customize the appearance of dayView
- (void)calendar:(JTCalendarManager *)calendar prepareDayView:(JTCalendarDayView *)dayView
{
    // Today
    if([_calendarManager.dateHelper date:[NSDate date] isTheSameDayThan:dayView.date]){
        dayView.circleView.hidden = NO;
        dayView.circleView.backgroundColor = [UIColor blueColor];
        dayView.dotView.backgroundColor = [UIColor whiteColor];
        dayView.textLabel.textColor = [UIColor whiteColor];
    }
    // Selected date
    else if(_dateSelected && [_calendarManager.dateHelper date:_dateSelected isTheSameDayThan:dayView.date]){
        dayView.circleView.hidden = NO;
        dayView.circleView.backgroundColor = [UIColor redColor];
        dayView.dotView.backgroundColor = [UIColor whiteColor];
        dayView.textLabel.textColor = [UIColor whiteColor];
    }
    // Other month
    else if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
        dayView.circleView.hidden = YES;
        dayView.dotView.backgroundColor = [UIColor redColor];
        dayView.textLabel.textColor = [UIColor lightGrayColor];
    }
    // Another day of the current month
    else{
        dayView.circleView.hidden = YES;
        dayView.dotView.backgroundColor = [UIColor redColor];
        dayView.textLabel.textColor = [UIColor blackColor];
    }
    
    if([self haveEventForDay:dayView.date]){
        
        dayView.dotView.hidden = NO;
    }
    else{
        dayView.dotView.hidden = YES;
    }
}
//calendar:didTouchDayView:此方法用于在一个dayView的触摸作出响应。对于为例，你可以指示显示再过一个月，如果dayView是从另一个月份。
- (void)calendar:(JTCalendarManager *)calendar didTouchDayView:(JTCalendarDayView *)dayView
{
    _dateSelected = dayView.date;
    _date=[[self dateFormatter]stringFromDate:_dateSelected];
    [self loadData];
    [_calendarTableView reloadData];
    NSLog(@"%@",_dateSelected);
    NSLog(@"%@", _date);
    // Animation for the circleView
    dayView.circleView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
    [UIView transitionWithView:dayView
                      duration:.3
                       options:0
                    animations:^{
                        dayView.circleView.transform = CGAffineTransformIdentity;
                        [_calendarManager reload];
                    } completion:nil];
    
    
    // Don't change page in week mode because block the selection of days in first and last weeks of the month
    if(_calendarManager.settings.weekModeEnabled){
        return;
    }
    
    // Load the previous or next page if touch a day from another month
    
    //从另一个一个月装入一个或下一个页面，如果触摸了一天
    if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
        if([_calendarContentView.date compare:dayView.date] == NSOrderedAscending){
            [_calendarContentView loadNextPageWithAnimation];
        }
        else{
            [_calendarContentView loadPreviousPageWithAnimation];
        }
    }
}

#pragma mark - CalendarManager delegate - Page mangement

// Used to limit the date for the calendar, optional
//用于限制日历日期
- (BOOL)calendar:(JTCalendarManager *)calendar canDisplayPageWithDate:(NSDate *)date
{
    
    return [_calendarManager.dateHelper date:date isEqualOrAfter:_minDate andEqualOrBefore:_maxDate];
}

- (void)calendarDidLoadNextPage:(JTCalendarManager *)calendar
{
    _month=[[self dateFormatter2]stringFromDate:calendar.date];
    NSLog(@"向后滑动%@", _month);
    [self createEvents];
    
    NSLog(@"Next page loaded:::%@",calendar.date);
}

- (void)calendarDidLoadPreviousPage:(JTCalendarManager *)calendar
{
    _month=[[self dateFormatter2]stringFromDate:calendar.date];
    NSLog(@"向前滑动%@", _month);
    [self createEvents];
    NSLog(@"Previous page loaded");
}

#pragma mark - Fake data

- (void)createMinAndMaxDate
{
    _todayDate = [NSDate date];
    
    // Min date will be 2 month before today
    _minDate = [_calendarManager.dateHelper addToDate:_todayDate months:-6];
    
    // Max date will be 2 month after today
    _maxDate = [_calendarManager.dateHelper addToDate:_todayDate months:6];
}

// Used only to have a key for _eventsByDate
- (NSDateFormatter *)dateFormatter
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        //dateFormatter.dateFormat = @"dd-MM-yyyy";
        dateFormatter.dateFormat = @"yyyyMMdd";
    }
    
    return dateFormatter;
}
- (NSDateFormatter *)dateFormatter2
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        //dateFormatter.dateFormat = @"dd-MM-yyyy";
        dateFormatter.dateFormat = @"yyyyMM";
    }
    
    return dateFormatter;
}


- (BOOL)haveEventForDay:(NSDate *)date
{
    NSString *key = [[self dateFormatter] stringFromDate:date];
    
    if((_eventsByDate[key] && [_eventsByDate[key] count] > 0)||(_eventsByDate2[key] && [_eventsByDate2[key] count] > 0)||(_eventsByDate3[key] && [_eventsByDate3[key] count] > 0)){
        return YES;
    }
    
    return NO;
    
}

- (void)createEvents
{
    if([AppMonitor checkIsLogin]){
        NSUserDefaults *userData=[NSUserDefaults standardUserDefaults];
        NSString *userID=[userData objectForKey:@"userId"];
        _doctorId=userID;
        NSString *url = [NSString stringWithFormat:@"/docSchedule/getScheByMonth?doctorId=%@&month=%@",_doctorId,_month];
        [AppMonitor parseDicByUrl:url withSuccessBlock:^(NSData *successDic) {
            NSDictionary *dataInfo=[NSJSONSerialization JSONObjectWithData:successDic options:0 error:nil];
            
            for(id k in dataInfo){
                NSLog(@"%@", k);
                NSString *key;
                
                if([k intValue]<10){
                    key=[[NSString alloc]initWithFormat:@"%@0%@",_month,k];
                    NSLog(@"%@", key);
                }else{
                    key=[[NSString alloc]initWithFormat:@"%@%@",_month,k];
                }
                if(!_eventsByDate[key]){
                    _eventsByDate[key] = [NSMutableArray new];
                }
                NSDate *date=[[self dateFormatter] dateFromString:key];
                NSLog(@"%@", date);
                [_eventsByDate[key] addObject:date];
                NSLog(@"%@", key);
                [_calendarManager reload];
                
                
            }
            
        } andFailBlock:^(NSData *failDic) {
        }];
        
    }else{
        [AppMonitor jumpToLoginWithUIController:self.navigationController];
        
    }
    
    
}

- (void)createActivityEvents
{
    if([AppMonitor checkIsLogin]){
        NSUserDefaults *userData=[NSUserDefaults standardUserDefaults];
        NSString *userID=[userData objectForKey:@"userId"];
        _doctorId=userID;
        NSString *url = [NSString stringWithFormat:@"/actSchedule/getActByMonth?month=%@",_month];
        [AppMonitor parseDicByUrl:url withSuccessBlock:^(NSData *successDic) {
            NSDictionary *dataInfo=[NSJSONSerialization JSONObjectWithData:successDic options:0 error:nil];
            
            for(id k in dataInfo){
                NSLog(@"%@", k);
                NSString *key;
                
                if([k intValue]<10){
                    key=[[NSString alloc]initWithFormat:@"%@0%@",_month,k];
                    NSLog(@"%@", key);
                }else{
                    key=[[NSString alloc]initWithFormat:@"%@%@",_month,k];
                }
                if(!_eventsByDate3[key]){
                    _eventsByDate3[key] = [NSMutableArray new];
                }
                NSDate *date=[[self dateFormatter] dateFromString:key];
                NSLog(@"%@", date);
                [_eventsByDate3[key] addObject:date];
                NSLog(@"%@", key);
                [_calendarManager reload];
                
            }
            
        } andFailBlock:^(NSData *failDic) {
        }];
        
    }else{
        [AppMonitor jumpToLoginWithUIController:self.navigationController];
        
    }
}
#pragma 返回多少组数据
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_data count];
}
#pragma 返回怎样的cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId=@"cell";
    ScheduleTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellId];
    if(cell==nil){
        cell=[[[NSBundle mainBundle]loadNibNamed:@"ScheduleTableViewCell" owner:nil options:nil]firstObject];
    }
    ScheduleModel *scheduleModel=_data[indexPath.row];
    [cell setScheduleTableViewCell:scheduleModel];
    return cell;
}
#pragma cell点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ScheduleModel *scheduleModel=_data[indexPath.row];
    _scheduleModel=scheduleModel;
    if([scheduleModel.mark isEqual:@"0"]){
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        [self performSegueWithIdentifier:@"jumpToScheduleDetailAction" sender:nil];
    }
}
-(void)dismiss{
    [SVProgressHUD dismiss];
}
-(void)creatSuspendBtn{
    //悬浮按钮
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    [_button setBackgroundColor:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.80]];
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    
    
    //添加悬浮按钮方式一(直接添加):
    //  _button.frame = CGRectMake(screenWidth*0.5-28, screenHeight-74, 56, 56);
    //  [_button addTarget:self action:@selector(suspendBtnClick) forControlEvents:UIControlEventTouchUpInside];
    //[self.view addSubview:_button];
    //[self.view bringSubviewToFront:_button];
    
    
    //添加悬浮按钮方式二:(利用UIWindow)
    _button.frame = CGRectMake(0,0,50,50);
    _button.layer.cornerRadius = 25.0;
    [_button setBackgroundImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _button.clipsToBounds = TRUE;//去除边界
    [_button addTarget:self action:@selector(addSchedule) forControlEvents:UIControlEventTouchUpInside];
    
    //悬浮按钮所处的顶端UIWindow
    _window = [[UIWindow alloc] initWithFrame:CGRectMake(screenWidth*0.8, screenHeight*0.8, 40, 40)];
    //使得新建window在最顶端
    _window.windowLevel = UIWindowLevelAlert + 1;
    _window.backgroundColor = [UIColor clearColor];
    [_window addSubview:_button];
    //显示window
    [_window makeKeyAndVisible];
}
-(void)addSchedule{
    [self performSegueWithIdentifier:@"jumpToAddSchedule" sender:nil];
}



-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
   
    if([segue.identifier isEqualToString:@"jumpToScheduleDetailAction"]){
        DetailActivityViewController *detailActivityViewController=segue.destinationViewController;
        [detailActivityViewController initData:_scheduleModel];
        
    }
}

@end
